package com.lxw.station;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lxw.mutils.FileUtils;
import lombok.SneakyThrows;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.nio.charset.StandardCharsets;

public class AI {
    @SneakyThrows
    public static void main(String[] args) {

        String content = "写一篇关于deepseek的文章,以json格式输出,输出的 JSON 需遵守以下的格式：{\"title\": <文章标题>,\"entiry\": <文章实体>,\"summary\": <文章摘要>}";
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters()
                .stream()
                .filter(converter -> converter instanceof StringHttpMessageConverter)
                .forEach(converter -> ((StringHttpMessageConverter) converter).setDefaultCharset(StandardCharsets.UTF_8));

        String url = "http://10.19.248.124:8000/v1/chat/completions";
        String json = "{\"model\":\"deepseek-r1-distill-qwen-32b\",\"response_format\":{\"type\":\"json_object\"},\"messages\":[{\"role\":\"user\",\"content\":\"${content}\"}]}";
        json = json.replace("${content}", content);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<>(json, headers);
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        String body = exchange.getBody();
        System.out.println("body = " + body);
        // 解析 JSON
        JSONObject jsonObject = JSON.parseObject(body);

        // 获取 choices 数组中的第一个对象
        JSONObject firstChoice = jsonObject.getJSONArray("choices").getJSONObject(0);

        // 获取 message 对象
        JSONObject message = firstChoice.getJSONObject("message");

        // 提取 content 字段
        String contentResult = message.getString("content").split("</think>")[1];
        System.out.println(contentResult);
        String[] split = contentResult.split("\n");
        File file = new File("E:\\csdn\\develop_task\\deepseek\\DeepSeek：人工智能在工作中的多场景应用.md");
        File parentFile = file.getParentFile();
        if (!parentFile.exists()&&parentFile.mkdirs()) {
            FileUtils.write2File(file, split);
        }
    }
}
